﻿using System;
using System.Collections.Generic;
using System.Linq;

using Moe.ECamel.Common.Entities;
using Moe.ECamel.Common.Security;
using Moe.ECamel.Client.ServiceProxies;

namespace Moe.ECamel.Client.Controllers
{
	public class EmployeesController : EntityController<Employee>
	{
		public EmployeesController(int libraryId)
			: base(libraryId)
		{
		}

		private Employee _manager;
		public Employee Manager
		{
			get { return _manager; }
		}

		public ECamelError SetManager(Employee employee)
		{
			using (var serviceProxy = new EmployeeServiceProxy())
			{
				var error = serviceProxy.ChangeManager(this.ParentEntityId, employee.EmployeeId);
				if (error != null)
					return error;
			}

			this._manager = employee;
			return null;
		}

		public override Employee NewEntity()
		{
			var employee = base.NewEntity();
			employee.LibraryId = this.ParentEntityId;
			employee.IsActive = true;
			employee.User = new User();
			employee.User.SetDefaultValues();
			return employee;
		}

		public override ECamelError Create(Employee entity)
		{
			using (var serviceProxy = new EmployeeServiceProxy())
			{
				ECamelPasswordHasher.GenerateDefaultPassword(entity.User);
				return serviceProxy.CreateEmployee(entity);
			}
		}

		public override ECamelError Update(Employee entity)
		{
			using (var serviceProxy = new EmployeeServiceProxy())
			{
				return serviceProxy.UpdateEmployee(entity);
			}
		}

		public ECamelError UpdateStatus(Employee employee, bool active)
		{
			using (var serviceProxy = new EmployeeServiceProxy())
			{
				return serviceProxy.UpdateEmployeeStatus(employee.EmployeeId, active);
			}
		}

		protected override IList<Employee> LoadList()
		{
			using (var serviceProxy = new EmployeeServiceProxy())
			{
				List<Employee> tempList = serviceProxy.GetEmployeesByLibrary(this.ParentEntityId);

				// Refresh manager:
				_manager = (from e in tempList
							where e.User.UserRoles.Any(ur => ur.RoleId == Roles.Manager)
							select e).FirstOrDefault();

				return tempList;
			}
		}
	}
}